//
//  TestWrappedLayout.swift
//  Motion
//
//  Created by 悦月越悦 on 2021/3/8.
//

import SwiftUI

struct SearchRecord: View {
    @Binding var keyWords : [String]

    var body: some View {
        GeometryReader { geometry in
            self.generateContent(in: geometry)
        }
    }

    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return ZStack(alignment: .topLeading) {
            ForEach(self.keyWords, id: \.self.self) { keyWord in
                self.item(for: keyWord)
                    .padding([.horizontal, .vertical], 4)
                    .alignmentGuide(.leading, computeValue: { d in
                        if (abs(width - d.width) > g.size.width)
                        {
                            width = 0
                            height -= d.height
                        }
                        let result = width
                        if keyWord == self.keyWords.last! {
                            width = 0 //last item
                        } else {
                            width -= d.width
                        }
                        return result
                    })
                    .alignmentGuide(.top, computeValue: {d in
                        let result = height
                        if keyWord == self.keyWords.last! {
                            height = 0 // last item
                        }
                        return result
                    })
            }
        }
    }

    func item(for text: String) -> some View {
        Text(text)
            .customFont(12, true)
            .frame(width: 50,height: 30)
            .background(Color("sDeepGray"))
            .cornerRadius(16)
    }
}
